<?php

namespace App\Console\Commands;

use App\Facades\CommonPlatformRequestFacade;
use App\Facades\MoneyPlatformRequestFacade;
use App\Models\RepaySummary;
use App\Models\Traits\Repay;
use App\Models\User;
use App\Models\UserCertOcr;
use App\Models\UserInfo;
use App\ModelTransfers\Traits\BankCard;
use App\ModelTransfers\Traits\TUser;
use App\ModelTransfers\WsAccount\PayBindCard;
use App\ModelTransfers\WsFund\WsFund;
use App\ModelTransfers\WsLoans\LoanApply;
use App\ModelTransfers\WsLoans\LoanOrder;
use App\ModelTransfers\WsLoans\LoanProductTerm;
use App\ModelTransfers\WsUsers\AuthUserCert;
use App\ModelTransfers\WsUsers\TUserInfos;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use SebastianBergmann\CodeCoverage\Report\PHP;

class TransferCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'transfer:action {action=start|contacts} {--user=} {--start_time=} {--end_time=} {--repay=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'That\'s command list just for v100 version kskd transfer';

    /**
     * The console command action. month|common|money|help
     *
     * @var string
     */
    protected $action;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }

    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['start','back','setSummary','updateUser','contacts'])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'reptile','contacts'.");
            exit(1);
        }
    }

    protected function runAction()
    {
        if($this->action == 'updateUser'){
            $this->updateOldXinliuId();
        }else{
            $this->{$this->action}();
        }
    }


    protected function start()
    {
        $pid = getmypid();
        $t0 = microtime(true);
        $getRepay = $this->option('repay'); //true 只更新还款记录
        $getUserId = $this->option('user');
        $startTime = $this->option('start_time');
        $endTime = $this->option('end_time');
        $term = LoanProductTerm::where('is_valid', 1)->get(['product_code', 'loan_channel', 'term_no', 'service_rate']);
        $kskdUserId = User::whereNotNull('old_kskd_user_id')->pluck('old_kskd_user_id');
        $oldUserPhoneList = User::whereNotNull('old_kskd_user_id')->pluck('phone_num')->toArray(); //获取原卡贷迁移过来的手机号码列表
        $userPhoneList = User::pluck('phone_num')->toArray();
        $certkskdUserId = UserCertOcr::whereNotNull('old_kskd_user_id')->pluck('old_kskd_user_id');
        $certkskdUserId  = $certkskdUserId ? array_unique($certkskdUserId->toArray()) :[];
        //非晋商光大
        $loanUserId1 = DB::connection('transfer')->table('ws_loan.loan_order as  b')
            ->select('c.user_id')
            ->join('ws_loan.loan_apply as c','c.id','=','b.apply_id')
            ->join('ws_loan.loan_approve as  d','c.id','=','d.id')
            ->whereIn('c.apply_status',['7','8','9','10'])
            ->where('d.is_valid',1)
            ->where('b.is_valid',1)
            ->groupBy('c.user_id')
            ->pluck('user_id')->toArray();

        //晋商
        $loanUserId2 =DB::connection('transfer')->table('ws_fund.uni_fund_order as a')
            ->select("c.user_id")
            ->join('ws_loan.loan_order as b','a.apply_id','=', 'b.apply_id')
            ->join('ws_loan.loan_apply as c','c.id','=','b.apply_id')
            ->whereIn('a.status',[120,121,123,122])
            ->where('b.is_valid',1)
            ->where('c.loan_channel','LCC201709190010')
            ->groupBy('c.user_id')->pluck('user_id')->toArray();
        //光大
        $loanUserId3 = DB::connection('transfer')->table('ws_loan.loan_order as b')->select("c.user_id")
            ->join('ws_loan.loan_apply as c','c.id','=','b.apply_id')
            ->join('ws_loan.loan_approve as d','c.id','=', 'd.id')
            ->whereIn('c.apply_status',['7','8','9','10'])
            ->where('d.is_valid',1)
            ->where('b.is_valid',1)
            ->where('b.order_status',2)
            ->groupBy('c.user_id')->pluck('user_id')->toArray();
        //老光大
        $loanUserId4 =  DB::connection('transfer')->table('ws_loan.loan_order as b')
            ->select("c.user_id")
            ->join('ws_loan.loan_apply as c','c.id','=','b.apply_id')
            ->join('ws_loan.loan_approve as d','c.id','=','d.id')
            ->join('ws_xinliu.loan_order as e','c.id','=','e.apply_id')
            ->whereIn('c.apply_status',['7','8','9','10'])
            ->where('d.is_valid',1)
            ->where('b.is_valid',1)
            ->where('b.order_status',2)
            ->where('c.loan_channel','LCC201709190009')
            ->groupBy('c.user_id')
            ->pluck('user_id')
            ->toArray();
        $loanUserTotal = array_unique(array_merge($loanUserId1,$loanUserId2,$loanUserId3,$loanUserId4));
        TUserInfos::where(['partner_id' => 'ws'])
            ->whereNotnull('real_name')
            ->when($getRepay, function ($query) {
                $repay_user_ids = LoanApply::whereIn('id', function ($query) {
                    return $query->select('apply_id')
                        ->from('ws_loan.loan_repay')
                        ->groupBy('apply_id')
                        ->get();
                })
                    ->groupBy('user_id')
                    ->select('user_id')
                    ->pluck('user_id')->toArray();
                return $query->whereIn('id', $repay_user_ids);
            })
            ->when($getUserId,function($query) use ($getUserId){
                return $query->where('id','=',$getUserId);
            })
            ->when($startTime,function($query) use($startTime){
                return $query->where('create_date','>=',$startTime);
            })
            ->when($endTime,function($query) use ($endTime){
                return $query->where('create_date','<=',$endTime);
            })
            ->chunk(200, function ($userList) use ($kskdUserId,$term,$loanUserTotal,$userPhoneList, $oldUserPhoneList,$certkskdUserId, $pid) {
            foreach ($userList as $user) {
                if (in_array($user->phone, $oldUserPhoneList)) {
                    continue ;
                }
                $t1 = microtime(true);
                try {
                    //导入用户
                    $newUserId = TUserInfos::transfer($user,$userPhoneList);
                    $t2 = microtime(true);
                    PayBindCard::transfer($user,$newUserId);
                    AuthUserCert::transfer($user,$newUserId,$certkskdUserId);
                    $t3 = microtime(true);
                    $transList =  LoanOrder::moveLoanRequestByDB($user->id);
                    $t4 = microtime(true);
                    $applyList = [];
                    if(in_array($user->id,$loanUserTotal)){
                        $applyList = LoanApply::transfer($transList,$user,$newUserId,$term);
                    }

                    $t5 = microtime(true);
                    \App\ModelTransfers\Traits\Repay::transfer($applyList);
                    $t6 = microtime(true);
                    Log::debug('transfer_log', ['pid' => $pid, 'time' => sprintf('用户Id为%s手机号为%s的数据已插入完成,插入用户耗时%s秒,插入银行卡耗时%s秒，插入授信记录耗时%s秒,插入放款记录耗时%s秒，插入还款耗时%s秒，新Id为%d,总耗时%s秒' . PHP_EOL,
                        $user->id,
                        $user->phone,
                        round($t2 - $t1,2),
                        round($t3 - $t2,2),
                        round($t4 - $t3,2),
                        round($t5 - $t4,2),
                        round($t6 - $t5,2),
                        $newUserId,
                        round(microtime(true) - $t1,2))]);
                } catch (\Exception $e) {
                    Log::debug('transfer_exception', [
                        'uid' => $newUserId,
                        'old_uid' => $user->id,
                        'message' => $e->getMessage(),
                        'file' => $e->getFile(),
                        'line' => $e->getLine(),
                    ]);
                    $this->back($newUserId);
                }
            }
        });
        Log::debug('transfer_log', [
            'pid' => $pid,
            'time' => sprintf('总耗时%s秒' . PHP_EOL, round(microtime(true) - $t0,2)),
            'done' => true,
        ]);
    }


    public function  back($userId = '')
    {
       empty($userId) && $userId = $this->option('user');
       try{
           if(\App::environment('local')){
               $this->info('老哥，我们数据迁移要删除了！！！，开始啦');
           }
           //迁移授信记录返回
           LoanOrder::RollBack($userId);
           TUserInfos::removeTransfer($userId);
           BankCard::removeTransfer($userId);
           LoanApply::removeTransfer($userId);
           \App\ModelTransfers\Traits\Repay::removeTransfer($userId);
           AuthUserCert::removeTransfer($userId);
           TUserInfos::removeUserGlobal($userId);
       }catch (\Exception $e){
           Log::debug('transfer_back_exception', [
               'uid' => $userId,
               'message' => $e->getMessage(),
               'file' => $e->getFile(),
               'line' => $e->getLine(),
           ]);
       }
    }

    public function setSummary(){
        $summaryInfo = RepaySummary::select('trans_id','id','uid')->where('data_type','2')->chunk(1000, function ($summaryInfo) {
            foreach ($summaryInfo as $k => $v){
                //老光大
                $loanUserId4 =  DB::connection('transfer')->table('ws_xinliu.loan_order as b')
                    ->select('channel_user_id','channel_order_id')
                    ->where('apply_id',$v->trans_id)
                    ->first();
                if($loanUserId4){
                    $updateSummary = [
                        'transfer_loan_id' => $loanUserId4->channel_order_id
                    ];
                    User::where('id',$v->uid)->update(['channel_user_id' => $loanUserId4->channel_user_id]);
                    RepaySummary::where('id',$v->id)->update($updateSummary);
                }
            }
        });
    }


    /**
     * Description:
     * Author: liuju
     * DateTime: 2019-03-20 17:57
     */
    public function  updateOldXinliuId()
    {
        $data = $this->getXlsData();
        foreach($data[0] as $key=> $item) {
           $userId = RepaySummary::where('loan_id',$item[0])->value('uid');
           if($userId){
               User::where('id',$userId)->whereNull('old_xinliu_id')->update(['old_xinliu_id'=>$item[1]]);
           }
        }
        echo 'success'.PHP_EOL;
    }


    public  function getXlsData()
    {
        $path = dirname(dirname(dirname(__DIR__))) . '/document/loanId_map_user_20190321.xls';
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
        $cells = [];
        // $cells 是包含 Excel 表格数据的数组
        foreach ( $spreadsheet->getWorksheetIterator() as $cell ) {
         $cells[] =  $cell->toArray();
        }
        return $cells;
    }

    //todo 联系人补签
    public function contacts()
    {
        //获取原卡贷数据用户已存在联系人的uid
        $test = UserInfo::leftJoin('users as a', function ($join) {
                $join->on('user_infos.user_id', '=', 'a.id')
                    ->whereNotNull('a.old_kskd_user_id');
            })
            ->toSql();
        print_r($test);exit;
//            ->pluck('a.id');
        RepaySummary::where('repay_summaries.data_type', RepaySummary::DATA_TYPE_TWO)
            ->where('repay_summaries.data_type', RepaySummary::DATA_TYPE_TWO)
            ->select(['uid', 'trans_id'])
            ->chunk(5, function ($summaries) {
                print_r($summaries);exit;
            });
        $this->info('contacts_transfer_cron_done');
    }



}
